//
//  HelpersViewController.m
//  YYZB
//
//  Created by 顾悦 on 16/3/30.
//
//

#import "HelpersViewController.h"

#import "ProjectsViewController.h"

#import "DOPDropDownMenu.h"
#import "UIImageView+OnlineImage.h"
#import "SVPullToRefresh.h"
#import "HelperTableViewCell.h"
#import "ThemeColor.h"

#import "Project.h"
#import "Helper.h"

#import "HelperWebService.h"

#import "ClientWebViewController.h"

@interface SortItem : NSObject

- (instancetype)initWithCode:(NSString *)code title:(NSString *)title;

@property (nonatomic, copy) NSString *code;
@property (nonatomic, copy) NSString *title;

@end

@implementation SortItem

- (instancetype)initWithCode:(NSString *)code title:(NSString *)title {
    SortItem *item = [self class].new;
    item.code = code;
    item.title = title;
    return item;
}

@end

@interface HelpersViewController () <UITableViewDataSource, UITableViewDelegate, DOPDropDownMenuDataSource, DOPDropDownMenuDelegate, ProjectsViewDelegate>

@property (weak, nonatomic) IBOutlet UIButton *projectsButton;
@property (weak, nonatomic) IBOutlet UITableView *tableView;
@property (strong, nonatomic) DOPDropDownMenu *menu;

@property (strong, nonatomic) NSArray<SortItem *> *sortItems;
@property (strong, nonatomic) NSArray<Helper *> *items;
@property (copy, nonatomic) NSString *selectSortItemCode;
@property (strong, nonatomic) Project *project;
@property (nonatomic) NSUInteger pageIndex;
@property (nonatomic) NSUInteger pageSize;

@property (strong, nonatomic) HelperWebService *helperWebService;

@end

@implementation HelpersViewController

#pragma mark - 

- (DOPDropDownMenu *)menu {
    if (!_menu) {
        _menu = [[DOPDropDownMenu alloc] initWithOrigin:CGPointMake(0, 0) andHeight:44];
        _menu.dataSource = self;
        _menu.delegate = self;
    }
    
    return _menu;
}

- (NSArray<SortItem *> *)sortItems {
    if (!_sortItems) {
        _sortItems = @[
                       [[SortItem alloc] initWithCode:@"1" title:@"距离排序(从近到远)"],
//                       [[SortItem alloc] initWithCode:@"2" title:@"距离排序(从远到近)"],
                       [[SortItem alloc] initWithCode:@"3" title:@"评价排序(从高到低)"],
//                       [[SortItem alloc] initWithCode:@"4" title:@"评价排序(从低到高)"],
                       [[SortItem alloc] initWithCode:@"5" title:@"帮工等级(从高到低)"],
//                       [[SortItem alloc] initWithCode:@"6" title:@"帮工等级(从低到高)"],
                       ];
    }
    
    return _sortItems;
}

- (NSString *)selectSortItemCode {
    if (!_selectSortItemCode) {
        _selectSortItemCode = [_sortItems firstObject].code;
    }
    
    return _selectSortItemCode;
}

- (HelperWebService *)helperWebService {
    if (!_helperWebService) {
        _helperWebService = HelperWebService.new;
    }
    
    return _helperWebService;
}
//
//- (NSUInteger)pageIndex {
//    if (_pageIndex == 0) {
//        _pageIndex = 1;
//    }
//    
//    return _pageIndex;
//}

- (NSUInteger)pageSize {
    if (_pageSize == 0) {
        _pageSize = 100;
    }
    
    return _pageSize;
}

#pragma mark -

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    
    [self.view addSubview:self.menu];
    [self.view bringSubviewToFront:self.projectsButton];

    [self setupPullToRefresh];
    [self setupInfiniteScrolling];
    
    self.noDataView.backgroundColor = [ThemeColor lightLightGrayBGColor];
}

- (void)viewDidAppear:(BOOL)animated {
    [super viewDidAppear:animated];
    
    [self.tableView triggerPullToRefresh];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

#pragma mark - Navigation

- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    ProjectsViewController *phs = [segue destinationViewController];
    phs.delegate = self;
    phs.serviceID = self.serviceID;
    phs.serviceName = self.serviceName;
    phs.communityId = self.communityId;
    phs.menuData = self.menuData;
}

#pragma mark - 


#pragma mark -

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return [self.items count];
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    HelperTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"helperCell" forIndexPath:indexPath];
    
    Helper *h = self.items[indexPath.row];
    [cell.avatarImageView setOnlineImage:h.imagePath];
    cell.nameLabel.text = h.name;
    cell.levelLabel.text = h.level;
    cell.ratingView.value = [h.avgReviewScore floatValue];
    cell.ratingLabel.text = [NSString stringWithFormat:@"%@分", h.avgReviewScore];
    cell.alreadyServedLabel.text = [NSString stringWithFormat:@"已服务%@", h.serviceCount];
    cell.distanceLabel.text = [NSString stringWithFormat:@"%@KM", h.distance];
    
    return cell;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    Helper *h = self.items[indexPath.row];
    ClientWebViewController *webViewController = ClientWebViewController.new;
//    if (self.bizType == BizTypeMaintain) {
//        webViewController.HTMLURL = [NSString stringWithFormat:@"projects/helperDetail.html?id=%@&comid=%@&cate1Id=%@", h.ID, self.communityId, self.serviceID];
//    } else if (self.bizType == BizTypeCarWash) {
//        webViewController.HTMLURL = [NSString stringWithFormat:@"projects/helperDetail.html?id=%@&comid=%@&cate1Id=%@", h.ID, self.communityId, self.serviceID];
//    } else if (self.bizType == BizTypeSchool) {
//        webViewController.HTMLURL = [NSString stringWithFormat:@"projects/helperDetail.html?id=%@&comid=%@&cate1Id=%@", h.ID, self.communityId, self.serviceID];
//    } else if (self.bizType == BizTypeHouse) {
//        webViewController.HTMLURL = [NSString stringWithFormat:@"projects/helperDetail.html?id=%@&comid=%@&cate1Id=%@", h.ID, self.communityId, self.serviceID];
//    } else {
        webViewController.HTMLURL = [NSString stringWithFormat:@"../projects/helperDetail.html?id=%@&comid=%@&cate1Id=%@", h.ID, self.communityId, self.serviceID];
//    }
    webViewController.title = @"帮工详情";
    [self.navigationController pushViewController:webViewController animated:YES];
}

#pragma mark -

- (NSInteger)numberOfColumnsInMenu:(DOPDropDownMenu *)menu {
    return 2;
}

- (NSInteger)menu:(DOPDropDownMenu *)menu numberOfRowsInColumn:(NSInteger)column {
    if (column == 0) {
        return [self.sortItems count];
    } else {
        return 0;
    }
}

/**
 *  返回 menu 第column列 每行title
 */
- (NSString *)menu:(DOPDropDownMenu *)menu titleForRowAtIndexPath:(DOPIndexPath *)indexPath {
    if (indexPath.column == 0) {
        return self.sortItems[indexPath.row].title;
    } else {
        return self.project.name ?: @"项目";
    }
}

- (void)menuAnimationCompleted:(DOPDropDownMenu *)menu {
    [self.view bringSubviewToFront:self.projectsButton];
}

- (void)menu:(DOPDropDownMenu *)menu didSelectRowAtIndexPath:(DOPIndexPath *)indexPath {
    SortItem *s = self.sortItems[indexPath.row];
    self.selectSortItemCode = s.code;
    [self.tableView triggerPullToRefresh];
}

#pragma mark -

- (void)fetchItems {
    [self fetchItemsPagingEnabled:NO];
}

- (void)fetchItemsPagingEnabled:(BOOL)flag {
    if (!flag) {
        self.pageIndex = 0;
    }
//    [LoadingView show];
    [self.helperWebService getHelpersByServiceID:self.serviceID productID:self.project.ID ?: @"" communityId:self.communityId sortType:self.selectSortItemCode ?: @"" pageIndex:@(self.pageIndex + 1) pageSize:@(self.pageSize) completionHanlder:^(NSArray *items, NSError *error) {
        [LoadingView dismiss];
        if (error) {
            [LoadingView showToast:[error localizedDescription]];
        } else {
            NSMutableArray<Helper *> *ps = NSMutableArray.new;
            for (NSDictionary *i in items) {
                [ps addObject:[[Helper alloc] initWithDictionary:i]];
            }
            if (flag) {
                self.items = [[self.items arrayByAddingObjectsFromArray:ps] mutableCopy];
            } else {
                self.items = ps;
            }
            self.pageIndex ++;
        }
        dispatch_async(dispatch_get_main_queue(), ^{
            [self.tableView reloadData];
            if (!(self.tableView.pullToRefreshView.state == 0)) {
                [self.tableView.pullToRefreshView stopAnimating];
            }
            if (!(self.tableView.infiniteScrollingView.state == 0)) {
                [self.tableView.infiniteScrollingView stopAnimating];
            }
            self.noDataView.hidden = self.items.count;
        });
    }];
}

- (void)setupPullToRefresh {
    [self.tableView addPullToRefreshWithActionHandler:^{
        [self fetchItems];
    }];
    self.tableView.pullToRefreshView.titleLabel.text = @"";
}

- (void)setupInfiniteScrolling {
    [self.tableView addInfiniteScrollingWithActionHandler:^{
        [self loadMoreInfos];
    }];
}

- (void)loadMoreInfos {
    [self fetchItemsPagingEnabled:YES];
}

#pragma mark - 

- (void)didSelectProject:(Project *)p {
    self.project = p;
    self.selectSortItemCode = nil;
    [self.menu reloadData];
}

@end
